<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane label="产品直通率搜索"> </el-tab-pane>
      <avue-form ref="form" :option="tableOption" v-model="form">
        <template slot="btn">
          <el-button type="primary" size="small" class="el-icon-search" @click="handleSubmit">搜索</el-button>
          <el-button size="small" class="el-icon-delete" @click="handleCancel">清空</el-button>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="chart-tab tab-font">
      <el-tab-pane label="产品直通率明细"> </el-tab-pane>
      <el-row :gutter="20" class="chart-header">
        <el-col :span="6" v-if="displayForm.examineDate">时间:{{ `${displayForm.examineDate[0]} - ${displayForm.examineDate[1]}` }}</el-col>
        <el-col :span="4" v-if="displayForm.partNo">产品编码:{{ displayForm.partNo }}</el-col>
        <!--        <el-col :span="4" v-if="displayForm.partName">产品名称:{{ displayForm.partName }} </el-col>-->
        <!--        <el-col :span="4" v-if="displayForm.lotNo">批号:{{ displayForm.lotNo }} </el-col>-->
        <!--        <el-col :span="4" v-if="displayForm.partnerCode">客户编码:{{ displayForm.partnerCode }}</el-col>-->
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <chart-view class="chart-content" :chart-option="chartOption" :auto-resize="true" width="100%" />
          <avue-crud :option="option" :table-loading="loading" :data="data" :page="tablePage" @current-change="currentChange" @size-change="sizeChange" ref="crud">
            <!--            -->
          </avue-crud>
        </el-col>
      </el-row>
    </el-tabs>
  </basic-container>
</template>

<script>
import ChartView from '@/components/chart/index.vue';
import moment from 'moment';
import { tableOption, option } from '@/views/report/passthroughRate.js';
import { getPassthroughRate, getPassthroughRateChart } from '@/api/report/report';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'passthroughRate',
  mixins: [userConfig()],
  components: {
    ChartView,
    userTableConfig
  },
  data() {
    return {
      pageCode: 'PASSTHROUGH_RATE',
      form: {
        examineDate: this.getDefaultTime()
      },
      loading: false,
      data: [],
      option: tableOption,
      tablePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      tableOption: option,
      displayForm: {},
      chartOption: {
        title: {
          text: '产品直通率与产量趋势图',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{a0}: {c0}<br />{a1}: {c1}%'
        },
        legend: {
          top: '10%',
          tooltip: {
            show: true,
            formatter: function ({ name }) {
              return name === '直通率' ? '产品直通率为所有生产该产品的工单直通率的平均值' : '产量';
            }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            },
            nameTextStyle: {
              fontWeight: 'bold',
              fontSize: 16,
              padding: [0, 60, 20, 0]
            },
            name: '产量',
            nameLocation: 'start'
          },
          {
            type: 'value',
            nameTextStyle: {
              fontWeight: 'bold',
              fontSize: 16,
              padding: [0, 0, 20, 70]
            },
            axisLabel: {
              formatter: function (val) {
                return val + '%';
              }
            },
            name: '直通率',
            nameLocation: 'start'
          }
        ],
        series: [
          {
            name: '产量',
            type: 'line',
            data: [],
            color: ['#02a7f0']
          },
          {
            name: '直通率',
            type: 'line',
            data: [],
            yAxisIndex: 1,
            color: ['#f59a23']
          }
        ]
      }
    };
  },
  methods: {
    async onLoad(isRedrawChart) {
      const params = {
        startDate: this.form.examineDate[0],
        endDate: this.form.examineDate[1],
        partNo: this.form.partNo
      };
      const pageParams = {
        current: this.tablePage.currentPage,
        size: this.tablePage.pageSize
      };
      try {
        this.loading = true;
        // const res = await getPassthroughRate(params);
        const [tableData, resChartData] = await Promise.all([getPassthroughRate(Object.assign(params, pageParams)), getPassthroughRateChart(params)]);
        this.data = tableData.data.data.records || [];
        this.tablePage.total = tableData.data.data.total;
        this.tablePage.currentPage = tableData.data.data.current;
        this.tablePage.pageSize = tableData.data.data.size;
        const chartData = resChartData.data.data;
        if (isRedrawChart) {
          this.setChartOption(chartData);
        }
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(false);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(false);
    },
    setChartOption(data) {
      const xAxisData = [];
      const yieldData = [];
      const firstPassYieldData = [];
      data.forEach((item) => {
        xAxisData.push(item.windowDate);
        yieldData.push(item.yield);
        firstPassYieldData.push(item.firstPassYield);
      });
      const series = [
        {
          name: '产量',
          type: 'line',
          data: yieldData,
          color: ['#02a7f0']
        },
        {
          name: '直通率',
          type: 'line',
          data: firstPassYieldData,
          yAxisIndex: 1,
          color: ['#f59a23']
        }
      ];
      const xAxis = {
        type: 'category',
        boundaryGap: false,
        data: xAxisData
      };
      this.$set(this.chartOption, 'xAxis', xAxis);
      this.$set(this.chartOption, 'series', series);
    },
    handleSubmit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          this.displayForm = this._cloneDeep(this.form);
          this.onLoad(true);
          done();
        }
      });
    },
    handleCancel() {
      this.data = [];
      const series = this.chartOption.series.map((item) => ({ ...item, data: [] }));
      this.$refs.form.resetForm();
      this.displayForm = {};
      this.$set(this.chartOption, 'series', series);
    },
    getDefaultTime() {
      return [this.$moment(new Date()).subtract(7, 'days').format('yyyy-MM-DD'), this.$moment(new Date()).subtract(1, 'days').format('yyyy-MM-DD')];
    }
  }
};
</script>

<style scoped lang="scss">
.chart-tab {
  margin-top: 24px;
  height: calc(100vh - 350px);
  overflow-y: scroll;
}
.chart-header {
  display: flex;
  justify-content: center;
  align-items: center;
}
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
</style>
